package com.wjy.factory;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.io.Reader;
import java.util.Properties;

public class MyBatisFactory {

    private static final String config = "mybatis/config.xml";

    private static final String mysqlHome = "mysql/mysql-home.properties";
    private static final String mysqlCompany = "mysql/mysql-company.properties";

    private static SqlSessionFactory sqlSessionFactory = null;

    public static void initSqlSessionFactory() {

        try {

            Reader rConfig = Resources.getResourceAsReader(config);

            Properties pMysqlHome = Resources.getResourceAsProperties(mysqlHome);
            Properties pMysqlCompany = Resources.getResourceAsProperties(mysqlCompany);

            sqlSessionFactory = new SqlSessionFactoryBuilder().build(rConfig, "mysqlCompany", pMysqlCompany);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static SqlSession getSqlSession() {

        if (sqlSessionFactory == null) {
            initSqlSessionFactory();
        }

        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.SIMPLE, TransactionIsolationLevel.READ_COMMITTED);

        return sqlSession;

    }

}
